package com.chat.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chat.core.dao.ChatSessionDao;
import com.chat.core.dao.ChatSessionReadDao;
import com.chat.core.dao.UserDao;
import com.chat.core.entity.ChatSession;
import com.chat.core.entity.ChatSessionRead;
import com.chat.core.entity.User;
import com.chat.core.service.ChatSessionReadService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 聊天记录(ChatSessionRead)表服务实现类
 *
 * @author makejava
 * @since 2022-04-22 14:25:01
 */
@Service("chatSessionReadService")
public class ChatSessionReadServiceImpl extends ServiceImpl<ChatSessionReadDao, ChatSessionRead> implements ChatSessionReadService {

    @Resource
    ChatSessionDao sessionDao;
    @Resource
    UserDao userDao;

    @Override
    public List<ChatSessionRead> getSessionReadByUserId(Integer crtUserId, Integer userId) {
        QueryWrapper<ChatSession> wrapper = new QueryWrapper<>();
        wrapper.eq("CRT_USER_ID",crtUserId).eq("USER_ID",userId).or().
                eq("CRT_USER_ID",userId).eq("USER_ID",crtUserId);
        ChatSession session = sessionDao.selectOne(wrapper);
        QueryWrapper<ChatSessionRead> readQueryWrapper = new QueryWrapper<>();
        readQueryWrapper.eq("CHAT_SESSION_ID",session.getId());
        List<ChatSessionRead> chatSessionReads = this.getBaseMapper().selectList(readQueryWrapper);
        return  chatSessionReads.stream().peek(x->{
            User user = userDao.selectById(x.getCrtUserId());
            x.setUser(user);
        }).collect(Collectors.toList());
    }

    @Override
    public void updateReadState(Integer crtUserId, Integer userId) {
        QueryWrapper<ChatSession> wrapper = new QueryWrapper<>();
        wrapper.eq("CRT_USER_ID",crtUserId).eq("USER_ID",userId).or().
                eq("CRT_USER_ID",userId).eq("USER_ID",crtUserId);
        ChatSession session = sessionDao.selectOne(wrapper);
        QueryWrapper<ChatSessionRead> readQueryWrapper = new QueryWrapper<>();
        readQueryWrapper.eq("CHAT_SESSION_ID",session.getId());
        List<ChatSessionRead> chatSessionReads = this.getBaseMapper().selectList(readQueryWrapper);
        chatSessionReads = chatSessionReads.stream().peek(x->{
            if (x.getCrtUserId().equals(userId)){
                x.setReadState(1);
            }
        }).collect(Collectors.toList());
        boolean b = this.updateBatchById(chatSessionReads);
        Assert.isTrue(b,"操作失败！");
    }
}
